package cn.mrlong.base.ktnet.https

import java.security.KeyStore
import java.security.SecureRandom
import java.security.cert.X509Certificate
import java.util.*
import javax.net.ssl.*

/**
 * 作者：BINGO
 * 时间：2021/04/02 09:39
 */
object SSLSocketClient {
    public fun getSSLSocketFactory(): SSLSocketFactory {
        try {
            val sslContext = SSLContext.getInstance("SSL")
            sslContext.init(null, getTrustManager(), SecureRandom())
            return sslContext.socketFactory;
        } catch (e: Exception) {
            throw RuntimeException(e);
        }
    }

    //获取TrustManager
    private fun getTrustManager(): Array<TrustManager>? {
        return arrayOf(
            object : X509TrustManager {
                override fun checkClientTrusted(
                    chain: Array<X509Certificate?>?,
                    authType: String?
                ) {
                }

                override fun checkServerTrusted(
                    chain: Array<X509Certificate?>?,
                    authType: String?
                ) {
                }

                override fun getAcceptedIssuers(): Array<X509Certificate> {
                    return arrayOf<X509Certificate>()
                }
            }
        )
    }

    fun getHostnameVerifier(): HostnameVerifier {
        return HostnameVerifier { _, _ -> true }
    }

    fun getX509TrustManager(): X509TrustManager {
        var trustManager: X509TrustManager? = null
        try {
            val trustManagerFactory =
                TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
            trustManagerFactory.init(null as KeyStore?)
            val trustManagers = trustManagerFactory.trustManagers
            check(!(trustManagers.size != 1 || trustManagers[0] !is X509TrustManager)) {
                "Unexpected default trust managers:" + Arrays.toString(
                    trustManagers
                )
            }
            trustManager = trustManagers[0] as X509TrustManager
            return trustManager
        } catch (e: Exception) {
            e.printStackTrace()
            throw RuntimeException(e);
        }
    }
}